package com.quectel.core.module.application.service.impl;


import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.application.dao.ApplicationDao;
import com.quectel.core.module.application.dto.ApplicationAccessConfDto;
import com.quectel.core.module.application.dto.ApplicationAccessTemplateDto;
import com.quectel.core.module.application.dto.ApplicationDto;
import com.quectel.core.module.application.entity.ApplicationEntity;
import com.quectel.core.module.application.service.ApplicationAccessConfService;
import com.quectel.core.module.application.service.ApplicationAccessTemplateService;
import com.quectel.core.module.application.service.ApplicationService;
import com.quectel.core.module.device.dto.DeviceCategoryDto;
import com.quectel.core.module.device.dto.DeviceTypeDto;
import com.quectel.core.module.device.service.DeviceCategoryService;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author rananxin
 * @date 2021-11-02 11:07:02
 */
@DubboService
public class ApplicationServiceImpl implements ApplicationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationServiceImpl.class);

    private static final String APPLICATION_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "APPLICATION_CACHE_BY_ID:";

    private static final String APPLICATION_CACHE_BY_FLAGS = RedisCacheConstants.PROJECT_NAME + "APPLICATION_CACHE_BY_FLAGS:";

    @Autowired
    private ApplicationDao applicationDao;
    @Autowired
    private DeviceCategoryService deviceCategoryService;
    @Autowired
    private DeviceTypeService deviceTypeService;
    @Autowired
    private ApplicationAccessConfService applicationAccessConfService;
    @Autowired
    private ApplicationAccessTemplateService applicationAccessTemplateService;
    @Autowired
    private VillageService villageService;


    @Override
    public List<ApplicationDto> fetchByConfCode(String confCode, int shardingTotalCount, int shardingItem) {
        List<ApplicationDto> applicationDtos = CopyUtils.copyList(applicationDao.fetchByConfCode(confCode, shardingTotalCount, shardingItem), ApplicationDto.class);
        applicationDtos.forEach(this::paddingField);
        return applicationDtos;
    }

    @Override
    public List<ApplicationDto> fetchNeedTaskDataBySharding(int shardingTotalCount, int shardingItem) {
        return CopyUtils.copyList(applicationDao.fetchNeedTaskDataBySharding(shardingTotalCount, shardingItem), ApplicationDto.class);
    }

    @Override
    public List<ApplicationDto> selectCacheByFlag(String code, List<String> uniqueFlags, Map<String, Object> configMap
            , Long optionalTenantId, Long optionalDeviceTypeId) {

        StringBuilder sb = new StringBuilder();
        sb.append(APPLICATION_CACHE_BY_FLAGS);
        sb.append(code).append(":");
        for (String uniqueFlag : uniqueFlags) {
            sb.append(configMap.get(uniqueFlag)).append(":");
        }
        sb.deleteCharAt(sb.length() - 1);

        return CacheKit.cacheToRedis(() -> {
            ApplicationAccessConfDto applicationAccessConfDto = applicationAccessConfService.selectByCode(code);
            if (applicationAccessConfDto == null) {
                return null;
            }
            QueryWrapper<ApplicationEntity> queryWrapper = new QueryWrapper<ApplicationEntity>().eq("access_conf_id", applicationAccessConfDto.getId());

            for (String uniqueFlag : uniqueFlags) {
                queryWrapper.eq("access_conf->'$." + uniqueFlag + "'", configMap.get(uniqueFlag));
            }
            queryWrapper.eq(optionalTenantId != null, LambdaUtil.getFieldName(ApplicationEntity::getTenantId), optionalTenantId);
            queryWrapper.eq(optionalDeviceTypeId != null, LambdaUtil.getFieldName(ApplicationEntity::getDeviceTypeId), optionalDeviceTypeId);
            queryWrapper.last(SqlConstants.MYSQL_LIMIT_ONE);

            List<ApplicationEntity> applicationEntities = applicationDao.selectList(queryWrapper);
            return CopyUtils.copyList(applicationEntities, ApplicationDto.class);
        }, sb.toString(), SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS);
    }

    @Override
    public ApplicationDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                APPLICATION_CACHE_BY_ID + id,

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public ApplicationDto selectById(Long id) {
        ApplicationEntity entity = applicationDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, ApplicationDto.class));
    }

    @Override
    public List<ApplicationDto> queryList(Map<String, Object> params) {
        List<ApplicationEntity> list = applicationDao.queryList(params);
        List<ApplicationDto> result = CopyUtils.copyList(list, ApplicationDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private ApplicationDto paddingField(ApplicationDto dto) {
        if (dto != null) {
            DeviceCategoryDto deviceCategoryDto = deviceCategoryService.selectById(dto.getDeviceCategoryId());
            if (deviceCategoryDto == null) {
                deviceCategoryDto = new DeviceCategoryDto();
            }
            dto.setDeviceCategory(deviceCategoryDto);

            DeviceTypeDto deviceTypeDto = deviceTypeService.selectById(dto.getDeviceTypeId());
            if (deviceTypeDto == null) {
                deviceTypeDto = new DeviceTypeDto();
            }
            dto.setDeviceType(deviceTypeDto);

            VillageDto villageDto = villageService.selectById(dto.getVillageId());
            if (villageDto == null) {
                villageDto = new VillageDto();
            }
            dto.setVillage(villageDto);

            ApplicationAccessTemplateDto applicationAccessTemplateDto = applicationAccessTemplateService.selectById(dto.getAccessTemplateId());
            if (applicationAccessTemplateDto == null) {
                applicationAccessTemplateDto = new ApplicationAccessTemplateDto();
            }
            dto.setApplicationAccessTemplate(applicationAccessTemplateDto);

            ApplicationAccessConfDto applicationAccessConfDto = applicationAccessConfService.selectCacheById(dto.getAccessConfId());
            if (applicationAccessConfDto == null) {
                applicationAccessConfDto = new ApplicationAccessConfDto();
            }
            dto.setApplicationAccessConf(applicationAccessConfDto);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return applicationDao.queryTotal(params);
    }

    @Override
    public Long save(ApplicationDto dto) {
        ApplicationEntity entity = CopyUtils.copyObj(dto, ApplicationEntity.class);
        entity.setId(Snowflake.nextId());
        applicationDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(ApplicationDto dto) {
        ApplicationEntity entity = CopyUtils.copyObj(dto, ApplicationEntity.class);
        applicationDao.updateById(entity);
        CacheKit.invalidRedisCache(APPLICATION_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void updateAllColumnById(ApplicationDto dto) {

        ApplicationEntity entity = CopyUtils.copyObj(dto, ApplicationEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, applicationDao);

        CacheKit.invalidRedisCache(APPLICATION_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void deleteById(Long id) {
        applicationDao.deleteById(id);
        CacheKit.invalidRedisCache(APPLICATION_CACHE_BY_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
